package com.example.service;

import com.alibaba.fastjson2.JSONObject;
import com.example.domain.Store;
import com.example.domain.User;
import com.example.domain.vo.StoreVO;
import com.example.mapper.StoreMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class StoreService {

    @Autowired
    private StoreMapper mapper;


    public PageInfo<StoreVO> selectPageList(Store store) {
        Integer pageNum = store.getPageNum();
        PageHelper.startPage(pageNum, 10);
        List<StoreVO> list = mapper.selectPageList(store);
        return new PageInfo<>(list);
    }

    public void save(Store store, User operator) {
        if (store.getStoreId() == null) {
            store.setCreateBy(operator.getNickName());
            store.setCreateTime(new Date());
            this.mapper.insert(store);
        } else {
            this.mapper.updateByPrimaryKeySelective(store);
        }
    }

    public Store selectById(Long id) {
        return this.mapper.selectByPrimaryKey(id);
    }

    public void deleteById(Long id) {
        this.mapper.deleteByPrimaryKey(id);
    }

    public List<JSONObject> options() {
        List<StoreVO> list = mapper.selectPageList(null);
        return list.stream()
                .map(item -> {
                    JSONObject json = new JSONObject();
                    json.put("value", item.getStoreId());
                    json.put("label", item.getName());
                    return json;
                }).collect(Collectors.toList());
    }
}
